cmake_minimum_required(VERSION 3.10.0)

project(grpc_demo VERSION 0.1.0 LANGUAGES C CXX)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# set(CMAKE_GENERATOR_PLATFORM WIN32)
message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}")
# 新增：判断Debug/Release构建类型
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    message(STATUS "当前构建类型: Debug (调试模式)")
elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
    message(STATUS "当前构建类型: Release (发布模式)")
endif()

if(MSVC)
    add_compile_options("/utf-8")
    # set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL") # 启用多线程调试DLL
endif()


list(APPEND CMAKE_PREFIX_PATH "C:/Program Files (x86)/grpc/debug/lib/cmake/grpc")
list(APPEND CMAKE_PREFIX_PATH "C:/Program Files (x86)/grpc/debug/cmake")

# add_definitions(-DPROTOBUF_USE_DLLS) # 启用动态链接库
set(protobuf_MODULE_COMPATIBLE TRUE)
find_package(Threads REQUIRED)
find_package(Protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)

# 1. 先声明 proto 文件
set(PROTO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/proto")
file(GLOB_RECURSE PROTO_FILES "${PROTO_DIR}/*.proto")
message(STATUS "PROTO_FILES collected: ${PROTO_FILES}")
# foreach(PROTO_FILE IN LISTS PROTO_FILES)
#     # list(APPEND PROTO_FILES ${PROTO_FILE})
#     message(STATUS "add PROTO_FILE: ${PROTO_FILE}")
# endforeach(PROTO_FILE IN LISTS ${PROTO_DIR})

# 2. 指定生成目录
set(PROTO_GEN_DIR "${CMAKE_CURRENT_BINARY_DIR}/gen/proto")
file(MAKE_DIRECTORY "${PROTO_GEN_DIR}")

# 3. 声明一个变量，用于存储生成的 proto 文件
set(PROTO_GEN_FILES)

# 4. 遍历文件，使用 add_custom_command 生成 proto 文件（替换原有 protobuf_generate_cpp）
foreach(PROTO_FILE ${PROTO_FILES})
    get_filename_component(PROTO_FILE_NAME ${PROTO_FILE} NAME_WE)
    set(PROTO_GEN_H ${PROTO_GEN_DIR}/${PROTO_FILE_NAME}.pb.h) # 注意带上目录
    set(PROTO_GEN_CC ${PROTO_GEN_DIR}/${PROTO_FILE_NAME}.pb.cc)
    add_custom_command(
        OUTPUT ${PROTO_GEN_H} ${PROTO_GEN_CC}
        COMMAND $<TARGET_FILE:protobuf::protoc> # 使用 protobuf 提供的 protoc 目标, 可以替换成 protobuf::protoc
        ARGS
        --cpp_out=${PROTO_GEN_DIR} # 指定 C++ 代码生成目录
        -I${PROTO_DIR} # 指定 proto 文件搜索路径
        ${PROTO_FILE} # 输入 proto 文件
        DEPENDS ${PROTO_FILES} # 依赖 proto 文件（文件更新时重新生成）
        COMMENT "Generating C++ protobuf files: ${PROTO_GEN_H}, ${PROTO_GEN_CC}"
    )
    list(APPEND PROTO_GEN_FILES ${PROTO_GEN_CC})
endforeach(PROTO_FILE ${PROTO_FILES})
message(STATUS "PROTO_GEN_FILES collected: ${PROTO_GEN_FILES}")

add_executable(grpc_demo main.cpp ${PROTO_GEN_FILES})

target_include_directories(grpc_demo
    PRIVATE
    ${PROTO_GEN_DIR}
)

target_link_libraries(grpc_demo
    PRIVATE
    gRPC::grpc++
    protobuf::libprotobuf
)
